import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/app/core/api';

@Component({
	selector: 'app-menu',
	templateUrl: './menu.component.html',
	styleUrls: ['./menu.component.scss'],
})
export class MenuComponent implements OnInit {
	url: string;
	menuList = [];
	@Input()
	isCollapsed: boolean;
	routerData;

	@Output()
	menuEvent: EventEmitter<string> = new EventEmitter<string>();

	constructor(private router: Router, private apiService: ApiService, private activatedRoute: ActivatedRoute) {
		this.apiService.post('获取当前管理员权限', {}).then((res: any) => {
			this.menuList = this.getTree(res.data.list);
			console.log(res.data);
		});
	}

	ngOnInit() {
		let temp = this.activatedRoute;
		while (temp.firstChild) {
			temp = temp.firstChild;
		}
		this.routerData = temp.snapshot.data;
	}
	public gotoPage(e) {
		this.router.navigate([e.frontPath]);
	}
	getTree(list) {
		const array = [],
			obj = {};
		let temp;
		list.forEach(element => {
			if (element.parentId === 0) {
				array.push(element);
			}
			if (element.frontPath && this.routerData && element.frontPath.indexOf(this.routerData.url) !== -1) {
				element.selected = true;
				temp = element;
			}
			obj[element.id] = element;
		});
		if (temp) {
			// obj[temp.parentId].isOpen = true;
		}
		list.forEach(element => {
			if (obj[element.parentId]) {
				obj[element.parentId].children ? obj[element.parentId].children.push(element) : (obj[element.parentId].children = [element]);
			}
		});
		return array;
	}
	clickSubMenu(item) {
		if (item.frontPath) {
			this.router.navigate([item.frontPath]);
			return false;
		} else {
			if (!item.isOpen) {
				item.isOpen = !item.isOpen;
			}
		}
	}
	selectMenu(item) {
		this.menuList.forEach(element => {
			if (element.id !== item.id) {
				element.isOpen = false;
			}
		});
	}
}
